import ccApi from "@rc/apis/cc/index.mjs";
import coursewareApi from "@rc/apis/rc/courseware.mjs";
import TreeProject from "@rc/pages/components/async/tree-project.vue";
import CascaderCourse from "@rc/pages/components/async/cascader-course.vue";
import FilterSearch from "./components/filter-search.vue";

let timer = null; // 存储轮询用的定时器

export default {
    name: 'copy-page',
	components: {
		TreeProject,
		CascaderCourse,
		FilterSearch
	},
	data() {
		return {
			isIngOnce: false, // 是否曾进入复制页面，只要进入过复制页面，不手动点击就不会返回列表页
			copyTotalNumber: null, // 当前复制的目标资源总数
			copySuccessNumber: null, // 复制完成，成功的资源总数
			copyFailNumber: null, // 复制完成，失败的资源总数
			searchLoading: false, // 列表搜索的加载状态
			projectId: "", // 当前选中的项目id
			treeData: [], // 课程列表
			isShowDialog: false, // 是否显示弹窗
			submitLoading: false, // 提交表单的加载状态
			filtrateForm: {
				pypYear: "", // 年份
				pypId: "", // 年份周期标识
				moduleType: "", // 模块类型
				moduleId: "" // 模块id
			}, // 列表检索表单项
			checkNodes: [], // 当前选中的节点集合
			dialogForm: {
				seriesCourseList: []
			} // 弹窗表单
		};
	},
	computed: {
		// 当前已复制完成的总数
		copyCompleteNumber() {
			if (this.copySuccessNumber === null || this.copyFailNumber === null) {
				return null;
			}
			return this.copySuccessNumber + this.copyFailNumber;
		},
		// 当前复制的状态，unknown未知，complete未复制或已复制完成，ing复制中
		copyState() {
			if (this.copyTotalNumber === null || this.copyCompleteNumber === null) {
				return "unknown";
			}
			if (this.isIngOnce || this.copyTotalNumber !== this.copyCompleteNumber) {
				return "ing";
			}
			return "complete";
		},
		// 当前复制的进度百分比
		copyProgress() {
			if (
				this.copyTotalNumber === null ||
				this.copyCompleteNumber === null ||
				this.copyTotalNumber === 0 ||
				this.copyCompleteNumber === 0
			) {
				return 0;
			}
			return Math.floor((this.copyCompleteNumber / this.copyTotalNumber) * 100);
		},
		treeEmptyText() {
			if (this.searchLoading) {
				return "";
			}
			if (!this.filtrateForm.pypYear) {
				return "请先选择年份";
			}
			if (!this.filtrateForm.pypId) {
				return "请先选择考试周期";
			}
			if (!this.filtrateForm.moduleType) {
				return "请先选择模块类型";
			}
			if (!this.filtrateForm.moduleId) {
				return "请先选择模块";
			}
			return "暂无数据";
		},
		// 当前选中的节点数量
		checkedSize() {
			let num = 0;
			this.checkNodes.forEach((i1) => {
				if (i1.level === 1 || i1.level === 2) {
					// 如果当前节点是父级并且不存在子级，那累计上当前父级的数量
					if (!this.checkNodes.some((i2) => i2.parentId === i1.id)) {
						num += i1.coursewareNum;
					}
				} else {
					num += 1;
				}
			});
			return num;
		}
	},
	methods: {
		// 修改选中的项目
		chooseProject(item) {
			// 修改绑定的项目id，使其他依赖的异步组件渲染新数据
			this.projectId = item.projectId || "";
		},
		// 树状懒加载处理函数
		loadNode(node, resolve) {
			if (node.level === 1) {
				// 点击课程查询篇章
				ccApi.queryChapterCopyList({
					data: {
						courseId: node.data.id,
						projectId: this.projectId
					},
					success: (data) => {
						resolve(
							data.map((i) => {
								const name = i.catalogRemark ? `${i.catalogName}（备注：${i.catalogRemark}）` : i.catalogName;
								return {
									name,
									id: i.catalogId,
									courseId: node.data.id,
									catalogId: i.catalogId,
									parentId: node.data.id,
									coursewareNum: i.coursewareNum,
									level: 2
								};
							})
						);
					}
				});
			} else if (node.level === 2) {
				// 点击篇章查询课件
				ccApi.queryCoursewareCopyList({
					data: {
						projectId: this.projectId,
						courseId: node.data.courseId,
						catalogId: node.data.id
					},
					success: (data) => {
						resolve(
							data.map((i) => ({
								id: i.coursewareId,
								name: i.coursewareName,
								courseId: node.data.courseId,
								catalogId: node.data.id,
								coursewareId: i.coursewareId,
								parentId: node.data.id,
								leaf: true,
								level: 3
							}))
						);
					}
				});
			} else {
				resolve([]);
			}
		},
		// 更新课程列表
		updateCourseList({ pypId, moduleId }) {
			this.searchLoading = true;
			ccApi.queryCourseCopyList({
				data: {
					pypId,
					modulId: moduleId
				},
				success: (data) => {
					this.treeData = data.map((i) => ({
						id: i.courseId,
						name: i.courseName,
						courseId: i.courseId,
						coursewareNum: i.coursewareNum,
						level: 1
					}));
				},
				complete: () => {
					this.searchLoading = false;
				}
			});
		},
		// 查询资源复制进度,并根据结果创建轮询任务或者结束任务
		queryCopyProgress() {
			coursewareApi.queryCopyProgress({
				success: ({ failNumber, succeedNumber, totalNumber }) => {
					this.copyTotalNumber = totalNumber;
					this.copySuccessNumber = succeedNumber;
					this.copyFailNumber = failNumber;
					if (totalNumber === failNumber + succeedNumber) {
						// 当前已不存在复制任务，结束轮询
						timer && clearInterval(timer);
						timer = null;
					} else if (timer === null) {
						this.isIngOnce = true;
						// 当前正在复制状态，并且不存在轮询任务，创建轮询任务
						timer = setInterval(() => {
							this.queryCopyProgress();
						}, 2000);
					}
				}
			});
		},
		// 关闭复制中页面
		async closeIngPage() {
			this.isIngOnce = false;
			this.filtrateSubmit(this.filtrateForm);
		},
		// 筛选项发生变化
		filtrateChange(data) {
			// 实时更新同步变量
			this.filtrateForm = JSON.parse(JSON.stringify(data));
		},
		filtrateSubmit(data) {
			this.checkNodes = [];
			// 四个筛选项都是必填项，若不存在，重置为空数据
			if (!data.pypYear || !data.moduleType || !data.pypId || !data.moduleId) {
				this.searchLoading = false;
				this.treeData = [];
				return;
			}
			this.updateCourseList(data);
		},
		// 点击列表复选框时
		checkChange() {
			const checkList = this.$refs.tree.getCheckedNodes();
			let num = 0;
			// 计算当前选中的课件数量
			checkList.forEach((i1) => {
				if (i1.level === 1 || i1.level === 2) {
					// 如果当前节点是父级并且不存在子级，那累计上当前父级的数量
					if (!checkList.some((i2) => i2.parentId === i1.id)) {
						num += i1.coursewareNum;
					}
				} else {
					num += 1;
				}
			});
			const maxSize = 500;
			if (num > maxSize) {
				// 选中后的课件数超过限值，重设为之前的值
				this.$refs.tree.setCheckedKeys(this.checkNodes.map((i) => i.id));
				this.$message.warning(`选择的课件数不能超过${maxSize}个`);
				return;
			}
			// 一切正常，缓存当前选中的节点
			this.checkNodes = checkList;
		},
		// 点击开始复制
		onClickCopy() {
			if (!this.checkNodes.length) {
				this.$message.warning("请先选择要复制的课件");
				return;
			}
			this.dialogForm.seriesCourseList = [];
			this.isShowDialog = true;
		},
		// 弹窗表单提交
		onSubmitDialog() {
			this.$refs.dialogForm.validate((isValid) => {
				if (!isValid) {
					return false;
				}
				// 格式化课件信息入参
				const courseInfoList = this.checkNodes.map((i) => ({
					courseId: i.courseId,
					catalogId: i.catalogId || "",
					coursewareId: i.coursewareId || ""
				}));
				// 格式化系列课信息入参
				const seriesCourseList = this.dialogForm.seriesCourseList.map((i) => ({
					teachRange: i[0],
					seriesCourseId: i[1]
				}));
				this.submitLoading = true;
				ccApi.addCoursewareCopyTask({
					data: {
						seriesCourseList,
						courseInfoList,
						projectId: this.projectId,
						userId: User.getUser().userId
					},
					success: ({ operationStatus, operationStatusDesc }) => {
						this.isShowDialog = false;
						this.isIngOnce = true;
						this.copyTotalNumber = 0; // 当前复制的目标资源总数
						this.copySuccessNumber = 0; // 复制完成，成功的资源总数
						this.copyFailNumber = 0; // 复制完成，失败的资源总数
						this.queryCopyProgress();
						if (operationStatus === "Y") {
							this.$message.success(operationStatusDesc);
						} else {
							this.$message.error(operationStatusDesc);
						}
					},
					complete: () => {
						this.submitLoading = false;
					}
				});
			});
		}
	},
	created() {
		// 每个账号只能同时开启一个资源复制的计划任务，页面初始化时查询复制状态
		this.queryCopyProgress();
	},
	destroyed() {
		// 关闭时销毁轮询定时器
		timer && clearInterval(timer);
		timer = null;
	}
};
